﻿using Infragistics.WebUI.UltraWebGrid;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using uMES.LeanManufacturing.ParameterDTO;
using uMES.LeanManufacturing.ReportBusiness;
using uMES.LeanManufacturing.DBUtility;

public partial class Custom_BwPlanManager_BwSynergicInfoApplyForm : BaseForm
{
    int m_PageSize = 30;
    uMESSynergicInfoBusiness synergicBal = new uMESSynergicInfoBusiness();
    uMESContainerBusiness containerBal = new uMESContainerBusiness();
    uMESCommonBusiness common = new uMESCommonBusiness();
    static string businessName = "外协管理";
    static string parentName = "SynergicInfo";
    protected void Page_Load(object sender, EventArgs e)
    {
        uMESMasterPage master = this.Master as uMESMasterPage;
        master.strNavigation = "当前位置：外协申请";
        master.strTitle = "外协申请";
        master.ChangeFrame(true);

        upageTurning.PageIndexChanged += new pageTurning.PageIndexChangedEventHandler(() => { SearchData(upageTurning.CurrentPageIndex); });
        
        if (!IsPostBack)
        {
            ClearMessage();

            if (Request["ContainerName"] != null)
            {
                string strContainerName = Request["ContainerName"];

                txtScan.Text = strContainerName;
                txtScan_TextChanged(null, null);
            }
        }
    }

    #region 提示信息
    /// <summary>
    /// 提示信息
    /// </summary>
    /// <param name="strMessage"></param>
    /// <param name="boolResult"></param>
    protected void ShowStatusMessage(string strMessage, Boolean boolResult)
    {
        string strScript = "<script>ShowMessage(\"" + strMessage + "\", " + boolResult.ToString().ToLower() + ");</script>";
        Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
    }

    /// <summary>
    /// 清除提示信息
    /// </summary>
    protected void ClearMessage()
    {
        string strScript = "<script>ShowMessage(\"\", true);</script>";
        LiteralControl child = new LiteralControl(strScript);
        WebAsyncRefreshPanel1.Controls.Add(child);
    }
    #endregion

    #region 事件
    protected void btnSearch_Click(object sender, EventArgs e)
    {
        ClearMessage();
        try
        { 
            ClearData(false,true,true);
            SearchData(1);
        }
        catch (Exception ex)
        {
            ShowStatusMessage(ex.Message, false);
        }
    }
    protected void gdContainer_ActiveRowChange(object sender, Infragistics.WebUI.UltraWebGrid.RowEventArgs e)
    {
        ClearMessage();

        ClearData(false,false,true);
        LoadSpecInfo(e.Row);
    }
    protected void btnReSet_Click(object sender, EventArgs e)
    {
        ClearMessage();

        Response.Redirect(Request.Url.AbsoluteUri);
    }
    protected void txtScan_TextChanged(object sender, EventArgs e)
    {
        ClearMessage();

        SearchData(1);
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        ClearMessage();
        try
        {
            ResultModel re = SaveData();
            ShowStatusMessage(re.Message, re.IsSuccess);
            if (re.IsSuccess)
            {
                ClearData(false, false, true);
                SearchData(1);
            }
        }
        catch (Exception ex)
        { 
            ShowStatusMessage(ex.Message, false);
        }
    }
    #endregion

    #region 方法
    /// <summary>
    /// 查询数据
    /// </summary>
    /// <param name="index"></param>
    void SearchData(int index)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["CurrentPageIndex"] = index.ToString();
        para["PageSize"] = m_PageSize.ToString();
        para["ProcessNo"] = txtProcessNo.Text.Trim();
        para["ContainerName"] = txtContainerName.Text.Trim();
        para["ProductName"] = txtProductName.Text.Trim();
        if (!string.IsNullOrWhiteSpace(txtScan.Text.Trim()))
        {
            para["ScanContainerName"] = txtScan.Text.Trim();
        }
        uMESPagingDataDTO result = synergicBal.GetCanApplySynergicData(para);
        this.gdContainer.DataSource = result.DBTable;
        this.gdContainer.DataBind();
        //给分页控件赋值，用于分页控件信息显示
        this.upageTurning.TotalRowCount = int.Parse(result.RowCount);
        this.upageTurning.RowCountByPage = m_PageSize;
    }
    /// <summary>
    /// 工序
    /// </summary>
    /// <param name="row"></param>
    void LoadSpecInfo(UltraGridRow row)
    {
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["WorkflowId"] = row.Cells.FromKey("WorkflowID").Text;
        para["ContainerID"] = row.Cells.FromKey("ContainerID").Text;

        //获取已报工工序信息
        DataTable dtReport = synergicBal.GetContainerReportInfo(para);
        if (dtReport.Rows.Count>0)
        {
            string strSpecList = string.Empty;
            for (int i=0;i<dtReport.Rows.Count;i++)
            {
                if (!string.IsNullOrEmpty(dtReport.Rows[i]["specid"].ToString()))
                {
                    strSpecList += "'" + dtReport.Rows[i]["specid"].ToString() + "',";
                }
            }

            if (strSpecList!=null)
            {
                strSpecList = strSpecList.TrimEnd(',');
                para["SpecList"] = strSpecList;
            }
        }

        para.Add("Sequence", row.Cells.FromKey("sequence").Text);

        DataTable dt = synergicBal.GetStepInfo(para);
        gdSpec.DataSource = dt;
        gdSpec.DataBind();
    }

    protected void gdSpec_DataBound(object sender, EventArgs e)
    {
        UltraGridRow activeRow = gdContainer.DisplayLayout.ActiveRow;
        int intQty = 0;
        if (activeRow != null)
        {
            if (activeRow.Cells.FromKey("Qty").Value != null)
            {
                intQty = Convert.ToInt32(activeRow.Cells.FromKey("Qty").Value.ToString());
            }
        }
        for (int i = 0; i < gdSpec.Rows.Count; i++)
        {
            string strSpecName = gdSpec.Rows[i].Cells.FromKey("SpecName").Value.ToString();
            gdSpec.Rows[i].Cells.FromKey("SpecNameDisp").Text = common.GetSpecNameWithOutProdName(strSpecName);

            if (gdSpec.Rows[i].Cells.FromKey("unitworktime").Value != null)
            {

                gdSpec.Rows[i].Cells.FromKey("totalworktime").Text = (intQty * Convert.ToDouble(gdSpec.Rows[i].Cells.FromKey("unitworktime").Text)).ToString();
            }
        }
    }
    
    /// <summary>
    /// 提交数据
    /// </summary>
    /// <returns></returns>
    ResultModel SaveData()
    {
        ResultModel re = new ResultModel(false, "");
        UltraGridRow activeRow = gdContainer.DisplayLayout.ActiveRow;
        if (activeRow == null)
        {
            re.Message = "请选择批次";
            return re;
        }
        DataTable dt = uMESCommonFunction.GetGridChooseInfo(gdSpec, null, "ckSelect");

        if (dt.Rows.Count == 0)
        {
            re.Message = "请选择工序";
            return re;
        }
        //判断是否连续
        string containerID= activeRow.Cells.FromKey("ContainerID").Text;
        string workflowID= activeRow.Cells.FromKey("WorkflowID").Text;
        if (dt.Rows.Count > 1)
        {
            for (int i = 1; i < dt.Rows.Count; i++)
            {
                int curSeq = int.Parse(dt.Rows[i]["sequence"].ToString());
                int preSeq = int.Parse(dt.Rows[i - 1]["sequence"].ToString());
                if (preSeq + 1 != curSeq)
                {
                    re.Message = "请选择连续的工序";
                    return re;
                }
                else
                {
                    //是否需要判断已经指派不能外协
                    if (OracleHelper.QueryDataByEntity(new ExcuteEntity("dispatchinfo", ExcuteType.selectAll)
                    {
                        WhereFileds = new List<FieldEntity> { new FieldEntity("containerid", containerID,FieldType.Str), new FieldEntity("workflowID", workflowID, FieldType.Str),
                        new FieldEntity("specid", dt.Rows[i]["SpecId"].ToString(),FieldType.Str)},
                        strWhere = " and parentid is not null "
                    }).Rows.Count > 0)
                    {
                        re.Message = "所选工序中有已经指派到人，不能外协！";
                        return re;
                    }
                }
            }
        }

        //是否需要判断已经指派不能外协
        if (OracleHelper.QueryDataByEntity(new ExcuteEntity("dispatchinfo", ExcuteType.selectAll)
        {
            WhereFileds = new List<FieldEntity> { new FieldEntity("containerid", containerID,FieldType.Str), new FieldEntity("workflowID", workflowID, FieldType.Str),
                        new FieldEntity("specid", dt.Rows[0]["SpecId"].ToString(),FieldType.Str)},
            strWhere = " and parentid is not null "
        }).Rows.Count > 0)
        {
            re.Message = "所选工序中有已经指派到人，不能外协！";
            return re;
        }
        Dictionary<string, string> para = new Dictionary<string, string>();
        para["ContainerId"] = activeRow.Cells.FromKey("ContainerID").Text;
        para["FromFactoryId"] = UserInfo["FactoryID"];
        para["SpecId"] = dt.Rows[0]["SpecId"].ToString();
        para["Sequence"] = dt.Rows[0]["Sequence"].ToString();
        para["Qty"] = activeRow.Cells.FromKey("Qty").Text;
        para["UomId"] = activeRow.Cells.FromKey("UomID").Text;
        para["WorkflowId"] = activeRow.Cells.FromKey("WorkflowID").Text;
        para["Status"] = "1";
        para["ReturnSpecID"] = dt.Rows[dt.Rows.Count - 1]["SpecId"].ToString();
        para["ReturnSequence"] = dt.Rows[dt.Rows.Count - 1]["Sequence"].ToString();
        para["ProposerId"]= UserInfo["EmployeeID"];
        para["SynergicInfoID"] = Guid.NewGuid().ToString();

        re = synergicBal.InsertSynergicApplyInfo(para);
        if (re.IsSuccess) 
        {
            #region 日志赋值
            MESAuditLog ml = new MESAuditLog();
            string ContainerID = activeRow.Cells.FromKey("ContainerID").Text;
            string ContainerName = activeRow.Cells.FromKey("ContainerName").Text;
            string specNames = dt.Rows[0]["SpecNameDisp"].ToString() + " 到 " + dt.Rows[dt.Rows.Count - 1]["SpecNameDisp"].ToString();//选中的外协起止
            ml.ParentID = para["SynergicInfoID"];//主键
            ml.ParentName = parentName;//表名
            ml.CreateEmployeeID = UserInfo["EmployeeID"];//人员ID
            ml.BusinessName = businessName;//模块名
            ml.OperationType = 0;//操作类型
            ml.Description = string.Format("工序外协申请:"+ specNames);
            ml.ContainerID = ContainerID;
            ml.ContainerName = ContainerName;
           common.SaveMESAuditLog(ml);
            #endregion
            re.Message = "保存成功";
        }
        return re;
    }
    ///清除数据
    void ClearData(bool isCondition, bool isGrid, bool isDetail)
    {
        if (isCondition)
        {
            txtScan.Text = ""; txtContainerName.Text = ""; 
            txtProcessNo.Text = ""; txtProductName.Text = "";
        }
        if (isGrid)
        {
            gdContainer.Rows.Clear();
        }
        if (isDetail)
        {
            gdSpec.Rows.Clear();
        }
    }
    #endregion

    protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            ClearMessage();
            UltraGridRow uldr = gdContainer.DisplayLayout.ActiveRow;
            if (uldr == null)
            {
                ShowStatusMessage("请选择订单记录", false);
                //Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, "<script>alert('请选择批次记录')</script>");
                return;
            }
            DataTable poupDt = new DataTable();
            poupDt.Columns.Add("ProductID");
            poupDt.Columns.Add("WorkflowID");
            poupDt.Columns.Add("ContainerID");
            poupDt.Columns.Add("ContainerName");
            DataRow newRow = poupDt.NewRow();
            newRow["ProductID"] = uldr.Cells.FromKey("ProductID").Text;
            newRow["WorkflowID"] = uldr.Cells.FromKey("Workflowid").Text;
            newRow["ContainerID"] = uldr.Cells.FromKey("ContainerID").Text;
            newRow["ContainerName"] = uldr.Cells.FromKey("ContainerName").Text;
            poupDt.Rows.Add(newRow);
            Session.Add("ProcessDocument", poupDt);
            string strScript = string.Empty;
            strScript = "<script>window.showModalDialog('../bwCommonPage/uMESDocumentViewPopupForm.aspx', '', 'dialogWidth: 700px; dialogHeight: 600px; status = no; center: Yes; resizable: NO; ')</script>";
            Infragistics.WebUI.Shared.CallBackManager.AddScriptBlock(Page, WebAsyncRefreshPanel1, strScript);
            
        }
        catch (Exception ex)
        {
            DisplayMessage(ex.Message, false);
        }
    }
}